﻿using System;
using System.Collections.Generic;
using Jayden.Dll.Core.Persistence;
using Jayden.Dll.Core.Persistence.Attributes;
using Jayden.Dll.Series.Providers;

namespace Jayden.Dll.Series
{
	[Table]
	public class ShowInfo : ObjectBase
	{
		private string m_Id;
		private string m_Title;
		private int m_RunTime;
		private DateTime? m_StartDate;
		private DateTime? m_EndDate;
		private int m_EpisodesCount;

		private List<EpisodeInfo> m_Episodes;
		private List<int?> m_Seasons;
		private Dictionary<int?, List<EpisodeInfo>> m_EpisodesBySeasons;

		public ShowInfo(UnitOfWork uow) : base(uow, 0) { }
		public ShowInfo(UnitOfWork uow, long id) : base(uow, id) { }

		[Field(PrimaryKey = true, AutoIncrement = true)]
		public long PkId { get { return (long)ObjectId[0]; } set { ObjectId[0] = value; } }
		[Field]
		public string Id { get { return m_Id; } set { m_Id = value; } }
		[Field]
		public string Title { get { return m_Title; } set { m_Title = value; } }
		[Field]
		public int RunTime { get { return m_RunTime; } set { m_RunTime = value; } }
		[Field]
		public DateTime? StartDate { get { return m_StartDate; } set { m_StartDate = value; } }
		[Field]
		public DateTime? EndDate { get { return m_EndDate; } set { m_EndDate = value; } }
		[Field]
		public int EpisodesCount { get { return m_EpisodesCount; } set { m_EpisodesCount = value; } }

		public List<EpisodeInfo> Episodes
		{
			get
			{
				if (m_Episodes == null && Id != null)
				{
					lock (this)
					{
						if (m_Episodes == null)
						{
							SQLiteEpisodeInfoDataAccess episodeProvider = UnitOfWork.DataAccessManager.GetDataAccess<EpisodeInfo>() as SQLiteEpisodeInfoDataAccess;
							m_Episodes = new List<EpisodeInfo>(episodeProvider.FindByShowInfoId(Id));
							m_Episodes.Sort();
						}
					}
				}
				return m_Episodes;
			}
			set { m_Episodes = value; }
		}
		public Dictionary<int?, List<EpisodeInfo>> EpisodesBySeasons
		{
			get
			{
				if (m_EpisodesBySeasons == null)
				{
					lock (Episodes)
					{
						if (m_EpisodesBySeasons == null)
						{
							m_EpisodesBySeasons = new Dictionary<int?, List<EpisodeInfo>>();
							List<EpisodeInfo> list = null;
							foreach (EpisodeInfo episode in Episodes)
							{
								if (!m_EpisodesBySeasons.TryGetValue(episode.Season, out list))
								{
									list = new List<EpisodeInfo>();
									m_EpisodesBySeasons.Add(episode.Season, list);
								}
								list.Add(episode);
							}
						}
					}
				}
				return m_EpisodesBySeasons;
			}
		}
		public List<int?> Seasons
		{
			get
			{
				if (m_Seasons == null)
				{
					lock (EpisodesBySeasons)
					{
						if (m_Seasons == null)
						{
							m_Seasons = new List<int?>(EpisodesBySeasons.Keys);
							m_Seasons.Sort();
						}
					}
				}
				return m_Seasons;
			}
		}

	}
}
